#!/usr/bin/python3

import sys

__HELP__ = """
draw.py [-f fname] @target

@target is specified like so:
 - //path/to/file:rule
 - rel_path/to/file:rule
 - :rule
"""
import repo_path
import build_file.graph
import config
import drawing.graph_draw

if __name__ == '__main__':
  draw_graph = drawing.graph_draw.DrawGraph()

  try:
    if len(sys.argv) < 1:
      print(sys.argv)
      print(__HELP__)
      exit()
    if len(sys.argv) > 2 and sys.argv[1] == '-f':
      fname = sys.argv[2]
      targets = sys.argv[3:]
    else:
      fname = None
      targets = sys.argv[1:]

    my_config = config.RepoConfig(__file__)
    my_config.load_config_filelist()

    with config.OpenGraphDatabase() as graph_cache:
      my_graph = build_file.graph.BuildRuleCachedGraph(my_config, graph_cache)

      for key in my_config.names_to_keys(targets, my_config.variants()[0]):
        draw_graph.add_rule(my_graph.get_rule_with_key(key))

      if fname:
        draw_graph.draw_to(fname)
      else:
        draw_graph.show()
  except repo_path.Error as e:
    print(e)
